#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include <cassert>
#include <cmath>

using namespace std;

static float minAbsDifference2(int* opidxBit, vector<float>& nums, float goal) {
  int minDeltaBit = 0x00;
  // float minSum = 1000;
  float delta = 0.0f;
  float minDelta = 2000.0f;
  float tmpSum = 0;
  int bit = 0x01, k = 0x01;
  int situation = pow(2, nums.size() + 1) - 1;
  for (int i = 0; i < situation; i++, bit++) {
    for (int j = 0; j < nums.size(); j++) {
      if ((bit & (k << j)) != 0) {
        tmpSum += nums[j];
      } else {
        tmpSum += 0;
      }
    }
    delta = tmpSum - goal;
    if (delta > 0 && delta < minDelta) {
      minDelta = delta;
      minDeltaBit = bit;
      // printf("[%0x]:%.02f\n", minDeltaBit, minDelta);
    }
    tmpSum = 0;
  }
  if (minDelta == 2000.0f) {
    minDeltaBit = 0xFFFF;
    minDelta = delta;
  }
  *opidxBit = minDeltaBit;
  return minDelta;
}

static void disp_res(const vector<float>& priceList, float delta, int idxBit,
                     float target)
{
  if (idxBit != 0) {
    printf("若恰好购买%.0f, 最小为差价:%.02f, 买这几个价格的商品:", target, delta);
    int k = 0x01;
    int count = 0;
    for (size_t i = 0; i < priceList.size(); i++)
    {
      if (idxBit & k) {
        cout << priceList[i]<< ", ";
        count++;
      }
      k <<= 1;
    }
    cout << " 共计:" << count << "件" << endl;
  }
}

int main(int argc, char *argv[]) {
	// Solution s;
  vector<float> priceList;
  // vector<float> priceList = {79, 339, 24.9, 71.8, 29.8, 15.2, 338, 18.5, 38.8, 15.8, 138};
  // vector<float> priceList = {4.36, 359, 24.9, 71.8, 29.8, 15.2, 18.5, 38.8, 15.8, 138};
  // vector<float> priceList = {4.36, 359, 24.9, 71.8, 29.8, 15.2, 18.5, 38.8, 15.8, 138};
  // vector<float> priceList = {4.36, 24.9, 71.8, 29.8, 15.2, 18.5, 38.8, 15.8, 138};
  // vector<int> priceListInt;
  float in = 0.0f;
  int count = 1;
  if (argc >= 2) {
    while (count < argc) {
      in = atof(argv[count]);
      priceList.push_back(in);
      count++;
    }
  } else  {
    printf("参数非法\n");
    return 0;
  }
  /// 运行时输入
  // while (1) {
  //   cout << "请输入待购商品原价(回车继续输入;输入≤0数值即开始计算):";
  //   cin >> in;
  //   if (in <= 0.0f)
  //     break;
    
  //   priceList.push_back(in);
  // }
  
  float ret = 0.0f;
  int idxBit = 0;
  float target = 300.0f;
  ret = minAbsDifference2(&idxBit, priceList, target);
  disp_res(priceList, ret, idxBit, target);
  
  target = 600.0f;
  ret = minAbsDifference2(&idxBit, priceList, target);
  disp_res(priceList, ret, idxBit, target);

  target = 900.0f;
  ret = minAbsDifference2(&idxBit, priceList, target);
  disp_res(priceList, ret, idxBit, target);

  target = 1200.0f;
  ret = minAbsDifference2(&idxBit, priceList, target);
  disp_res(priceList, ret, idxBit, target);

  cout << "==============================华丽分割线===================================" << endl;
  return 0;
}

